var socketio = require("socket.io");
var io;
var guestNumber = 1;
var nickNames = {};
var nameUsed = [];
var currentRoom = {};


exports.listen = function(server) {
    io = socketio.listen(server);
    io.set("log level", 1);
    io.sockets.on("connection", function(socket) {
        guestNumber = assignGuestName(socket, guestNumber, nickNames, namesUsed); //在用户连接时候赋予一个访客名
        joinRoom("socket", "Lobby"); //有用户连接的时候放到Lobby聊天室
        //处理用户小小，更名，以及聊天室的创建和更变
        handleMessageBroadCasting(socket, nickNames);
        handleNameChangeAttempts(socket, nickNames, namesUsed);
        handleRoomJoining(socket);
        //用户发起请求是，向其提供已经被占用的聊天室列表
        socket.on("rooms", function() {
                socket.emit("room", io.sockets.manager.rooms);
            })
            //定义用户断开连接后清除逻辑
        handleClientDisconnection(socket, nickNames, namesUsed);

    });
}


//分配昵称
function assignGuestName(socket, guestNumber, nickNames, namesUsed) {
    var name = "Guset" + guestNumber; //生成新名字
    nickNames[socket.id] = name;
    socket.emit("nameResult", {
        success: true,
        name: name
    });
    namesUsed.push(name); //存放已占用的昵称
    return guestNumber + 1; //增加生成的昵称计数器
}
//进入聊天室
function joinRoom(socket, room) {
    socket.join(room); //让用户进入房间
    currentRoom[socket.id] = room; //记录用户当前房间
    socket.emit("joinResult", { room: room }); //让用户知道他们进入了新房间
    //让其他人知道有新用户进入房间
    socket.broadcast.to(room).emit("message", {
        text: nickNames[socket.id] + ' has joined ' + room + '.'
    })
    var usersInRoom = io.sockets.clients(room);
    //如果房间里面不止有一个人 就汇总都有谁
    if (usersInRoom.length > 1) {
        var usersInRoomSummary = "Users currently in " + room + ": ";
        for (var index in usersInRoom) {
            var userSocketId = usersInRoom[index].id;
            if (userSocketId != socket.id) {
                if (index > 0) {
                    userInRoomSummary += " ,";
                }
                usersInRoomSummary += nickNames[userSocketId];
            }
        }
        usersInRoomSummary += ".";
        socket.emit("message", {text:usersInRoomSummary})
    }

}

//昵称更变请求
function handleNameChangeAttempts(socket,inckNames, namesUsed) {
    socket.on("nameAttempt", function(name) {
        //昵称不能以Guest开头
        if (name.indexOf("Guest") == 0) {
            socket.emit("nameResult", {
                success: false,
                message: "Names cant begin with 'Guest'."
            })
        } else {
            if (namesUsed.index(name) == -1) {
                var previousName = nickNames[socket.id];
                var previousNameIndex = namesUsed.indexOf(previousName);
                namesUsed.push(name);
                delete namesUsed[previousNameIndex]; //删除之前用的昵称
                socket.emit("nameResult", {
                    success: true,
                    name: name
                });
                socket.broadcast.to(currentRoom(socket.id)).emit("message", {
                    text: previousName + ' is now know as ' + name + '. '
                })
            } else {
                socket.emit('nameResult', {
                    success: false,
                    message: 'That name is already in use' //如果昵称被占用
                })
            }
        }
    })
}
//发射聊天消息
function handleMessageBroadcasting(socket) {
    socket.on("message", function(message) {
        socket.broadcast.to(message.room).emit("message", {
            text: nickNames[socket.id] + ' : ' + message.text
        })
    })
}
//创建房间
function handleRoomJoining(socket) {
    socket.on("join", function(root) {
        socket.leave(currentRoom[socket.id]);
        joinRoom(socket, room.newRoom);
    })
}
//用户断开
function handleClientDisconnection(socket) {
    socket.on('disconnect', function() {
        var nameIndex = nameUsed.indexOf(nickNames[socket.id]);
        delete namesUsed[nameIndex];
        delete nickNames[socket.id];
    })
}
